package org.example.order.controller;

import org.example.order.common.APIResponse;
import org.example.order.common.ResponseCode;
import org.example.order.entity.Ad;
import org.example.order.service.AdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/ad")
public class AdController {

    @Autowired
    private AdService service;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public APIResponse list() {
        List<Ad> list = service.getAdList();
        return new APIResponse(ResponseCode.SUCCESS, "查询成功", list);
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public APIResponse create(@RequestParam("imageFile") MultipartFile imageFile,
                              @RequestParam("link") String link) throws IOException {
        Ad ad = new Ad();
        ad.setImage(imageFile.getOriginalFilename());
        ad.setLink(link);
        service.createAd(ad);
        return new APIResponse(ResponseCode.SUCCESS, "创建成功");
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public APIResponse delete(@RequestParam("id") String id) {
        service.deleteAd(id);
        return new APIResponse(ResponseCode.SUCCESS, "删除成功");
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public APIResponse update(@RequestParam("id") String id,
                              @RequestParam(value = "imageFile", required = false) MultipartFile imageFile,
                              @RequestParam(value = "link", required = false) String link) throws IOException {
        Ad ad = new Ad();
        ad.setId(Long.parseLong(id));
        if (imageFile != null) {
            ad.setImage(imageFile.getOriginalFilename());
        }
        if (link != null) {
            ad.setLink(link);
        }
        service.updateAd(ad);
        return new APIResponse(ResponseCode.SUCCESS, "更新成功");
    }
}